<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <div style="display: flex;margin-right: 10px;float: left">
        <div class="addressTitle">
          商品类型
        </div>
        <div style="flex: 1;">
          <treeselect v-model="queryParams.productType" :options="productTypeOptions" :show-count="true"
                      @input="handleProductType()"
                      placeholder="请选所在地"  style="width: 200px"/>
        </div>
      </div>
      <el-form-item label="单位" prop="unit">
        <el-select v-model="queryParams.unit" placeholder="请选择计数单位" clearable>
          <el-option
            v-for="unit in unitOptions"
            :key="unit.id"
            :label="unit.name"
            :value="unit.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="unit in statusOptions"
            :key="unit.id"
            :label="unit.name"
            :value="unit.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="简称" prop="shortName">
        <el-input
          v-model="queryParams.shortName"
          placeholder="请输入简称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:product:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编码" align="center" prop="productCode" :show-overflow-tooltip="true"/>
      <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true"/>
      <el-table-column label="简称" align="center" prop="shortName" />
      <el-table-column label="价格（最近一次询价）" align="center" prop="price" />
      <el-table-column label="产品类型" align="center" prop="productTypeName" />
      <el-table-column label="计数单位" align="center" prop="unitName" />
      <el-table-column label="尺寸单位" align="center">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_product_cc_unit" :value="scope.row.ccUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="长" align="center" prop="longWith" />
      <el-table-column label="宽" align="center" prop="weight" />
      <el-table-column label="高" align="center" prop="height" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="warning" v-else>待维护</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" prop="detail" :show-overflow-tooltip="true"/>
<!--      <el-table-column label="库存" align="center" prop="storeNum"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleLookPriceLog(scope.row)"
            v-hasPermi="['wms:product:edit']"
          >历史价格</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:product:remove']"
          >删除</el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleStore(scope.row)"-->
<!--            v-hasPermi="['wms:product:remove']"-->
<!--          >设置库存</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="简称" prop="shortName">
              <el-input v-model="form.shortName" placeholder="请输入简称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="商品类型" prop="productType">
              <treeselect v-model="form.productType" :options="productTypeOptions" :show-count="true"
                          @input="handleProductType" placeholder="请选商品类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计数单位" prop="unit">
              <el-select v-model="form.unit" @change="handleUnitChange" placeholder="请选择计数单位" clearable>
                <el-option
                  v-for="unit in unitOptions"
                  :key="unit.id"
                  :label="unit.name"
                  :value="unit.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row :gutter="10">-->
<!--          <el-form-item>-->
<!--            <template slot="label">-->
<!--              占库存数-->
<!--              <el-tooltip class="item" effect="dark" content="每个商品占用库存的数量，这个数量是跟商品的计数单位绑定的" placement="bottom">-->
<!--                <i class="el-icon-warning-outline"></i>-->
<!--              </el-tooltip>-->
<!--            </template>-->
<!--            {{form.zyStoreNum}}-->
<!--          </el-form-item>-->
<!--        </el-row>-->
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="尺寸单位" prop="ccUnit">
              <el-select v-model="form.ccUnit" placeholder="请选择尺寸单位" clearable>
                <el-option
                  v-for="dict in dict.type.wms_product_cc_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="长" prop="longWith">
              <el-input v-model="form.longWith" placeholder="请输入长度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="宽" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入宽度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高" prop="height">
              <el-input v-model="form.height" placeholder="请输入高度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情" prop="detail">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入详情"
            v-model="form.detail">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品库存列表对话框 -->
    <el-dialog :title="title" :visible.sync="openStore" width="800px" append-to-body>
      <el-form inline>
        <el-form-item label="商品">
          {{productStore.productName}}
        </el-form-item>
        <el-form-item label="总库存数量">
          {{productStore.storeNum}}
        </el-form-item>
      </el-form>
      <el-table :data="productStoreList">
        <el-table-column label="仓库名称" align="center" prop="storeName" />
        <el-table-column label="容量" align="center" prop="maxCount" />
        <el-table-column label="剩余容量" align="center" prop="syCount" />
        <el-table-column label="库存数量" align="center" prop="productNum" />
        <el-table-column label="占库存数/每商品" align="center" prop="zyStoreNum" />
        <el-table-column label="操作" align="center" width="100px" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleOutputStore(scope.row, '0')"
            >入库</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleOutputStore(scope.row, '1')"
            >出库</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 设置库存对话框 -->
    <el-dialog :title="storeTitle" :visible.sync="openStoreSetting" width="500px" append-to-body>
      <el-form ref="productStoreForm" :model="productStoreForm" :rules="productStoreRules" label-width="90px">
        <el-form-item label="仓库">
          {{productStoreForm.storeName}}
        </el-form-item>
        <el-form-item v-if="productStoreForm.flag === '0'">
          <template slot="label">
            占库存数
            <el-tooltip class="item" effect="dark" content="每个商品占用库存的数量，这个数量是跟商品的计数单位绑定的" placement="bottom">
               <i class="el-icon-warning-outline"></i>
            </el-tooltip>
          </template>
          {{productStoreForm.zyStoreNum}}
        </el-form-item>
        <el-form-item label="剩余库存" v-if="productStoreForm.flag === '0'">
          {{productStoreForm.syCount}}
        </el-form-item>
        <el-form-item label="商品库存" v-else>
          {{productStoreForm.productNum}}
        </el-form-item>
        <el-form-item label="操作数量" prop="operatorNum">
          <el-input-number v-model="productStoreForm.operatorNum" placeholder="请输入操作数量" :min="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitProductStoreForm" v-loading="btnLoading">确 定</el-button>
        <el-button @click="productStoreCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 历史价格对话框 -->
    <el-dialog title="历史价格" :visible.sync="openLog" width="50%" append-to-body>
      <el-table :data="priceLogList">
        <el-table-column label="序号" align="center" type="index" width="50"/>
        <el-table-column label="价格" align="center" prop="price"/>
        <el-table-column label="时间" align="center" prop="createTime"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {listProduct, getProduct, delProduct, addProduct, updateProduct, getPriceLog} from "@/api/wms/product";
import { listProductTypeTree } from "@/api/wms/productType";
import { listUnitXlk } from "@/api/wms/unit";
import {getProductStoreList, settingProductStore} from "@/api/wms/store";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Product",
  dicts: ['wms_product_cc_unit'],
  components: {Treeselect},
  data() {
    return {
      //按钮加载
      btnLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      priceLogList: [],
      // 商品类型树
      productTypeOptions:[],
      // 单位列表
      unitOptions:[],
      // 状态列表
      statusOptions:[
        {
          id: '0',
          name: '正常'
        },
        {
          id: '2',
          name: '待维护'
        }
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openLog: false,
      // 库存列表弹出层
      openStore: false,
      // 设置库存弹出层
      openStoreSetting: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        shortName: null,
        productType: null,
        productCode: null,
        unit: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
          { max: 100, message: '商品名称长度最多 100个字', trigger: 'blur' }
        ],
        productType: [
          { required: true, message: "商品类型不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "计数单位不能为空", trigger: "blur" }
        ],
        ccUnit: [
          { required: true, message: "尺寸单位不能为空", trigger: "blur" }
        ],
        shortName: [
          { max: 50, message: '商品简称长度最多 50个字', trigger: 'blur' }
        ],
        detail: [
          { max: 255, message: '商品详情长度最多 255个字', trigger: 'blur' }
        ],
        longWith: [
          { pattern: /^(0|[1-9])\d{0,6}(\.\d{1,2})?$/, message: '商品长度只能是数值最大7位整数2位小数', trigger: 'blur' }
        ],
        weight: [
          { pattern: /^(0|[1-9])\d{0,6}(\.\d{1,2})?$/, message: '商品宽度只能是数值最大7位整数2位小数', trigger: 'blur' }
        ],
        height: [
          { pattern: /^(0|[1-9])\d{0,6}(\.\d{1,2})?$/, message: '商品高度只能是数值最大7位整数2位小数', trigger: 'blur' }
        ]
      },
      // 商品库存列表
      productStoreList: [],
      storeTitle: '',
      productStore: {
        productName: null,
        storeNum: null
      },
      productStoreForm: {
        operatorNum: 0,
        storeLogId: null,
        flag: '0',
        id: null,
        productId: null,
        productNum: null,
        syCount: null,
        storeName: null,
        zyStoreNum: null
      },
      productStoreRules: {
        operatorNum:[
          { required: true, message: "操作数量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getProductType();
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getProductType(){
      listProductTypeTree().then(res => {
        this.productTypeOptions = res.data;
      })
    },
    getUnitList(typeId){
      this.unitOptions = []
      listUnitXlk({productType: typeId}).then(res => {
        this.unitOptions = res.data;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.unitOptions = []
      this.form = {
        productCode: null,
        productName: null,
        shortName: null,
        productType: null,
        unit: null,
        detail: null,
        longWith: null,
        weight: null,
        height: null,
        ccUnit: '3',
        zyStoreNum: null
      };
      this.resetForm("form");
    },
    //商品类型变更事件
    handleProductType(val) {
      this.queryParams.unit = null
      this.form.unit = null
      this.getUnitList(val)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productCode = row.productCode || this.ids
      getProduct(productCode).then(response => {
        this.form = response.data;
        this.getUnitList(this.form.productType)
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 查询历史价格按钮操作 */
    handleLookPriceLog(row) {
      const productCode = row.productCode
      getPriceLog(productCode).then(response => {
        this.priceLogList = response.data;
        this.openLog = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.btnLoading = true
          if (this.form.productCode != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(f => {
              this.btnLoading = false
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(f => {
              this.btnLoading = false
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productCodes = row.productCode || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + productCodes + '"的数据项？').then(function() {
        return delProduct(productCodes);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 计数单位变更事件 */
    handleUnitChange(v){
      let unit = this.unitOptions.filter(item => item.id = v)
      this.form.zyStoreNum = unit.storeNum
    },
    /** 设置库存按钮操作 */
    handleStore(row) {
      this.productStore.productName = row.productName
      this.productStore.storeNum = row.storeNum ? row.storeNum : 0;
      this.productStoreForm.zyStoreNum = row.zyStoreNum
      this.productStoreForm.productId = row.productCode
      this.getProductStoreList(row.productCode)
    },
    getProductStoreList(productCode){
      getProductStoreList({productId: productCode}).then(response => {
        this.productStoreList = response.data
        this.title = '商品库存列表'
        this.openStore = true
      })
    },
    /** 商品设置出入库 */
    handleOutputStore(row, flag){
      this.productStoreForm.operatorNum = 0
      this.productStoreForm.storeLogId = row.storeLogId
      this.productStoreForm.flag = flag
      this.productStoreForm.id = row.id
      this.productStoreForm.productNum = row.productNum
      this.productStoreForm.storeName = row.storeName
      this.productStoreForm.syCount = row.syCount
      this.storeTitle = flag === '0' ? '商品入库' : '商品出库'
      this.openStoreSetting = true
    },
    /** 提交出入库 */
    submitProductStoreForm(){
      this.$refs["productStoreForm"].validate(valid => {
        if (valid) {
          let operatorNum = this.productStoreForm.zyStoreNum * this.productStoreForm.operatorNum
          let sign = 0
          if (this.productStoreForm.flag === '0' && this.productStoreForm.syCount < operatorNum){
            sign = 1
          }
          if (this.productStoreForm.flag === '1' && this.productStoreForm.productNum < this.productStoreForm.operatorNum){
            sign = 2
          }
          if (sign === 0) {
            this.btnLoading = true
            settingProductStore(this.productStoreForm).then(response => {
              this.$modal.msgSuccess("设置成功");
              this.openStoreSetting = false;
              if (this.productStoreForm.flag === '0'){
                this.productStore.storeNum += this.productStoreForm.operatorNum
              } else {
                this.productStore.storeNum -= this.productStoreForm.operatorNum
              }

              this.getProductStoreList(this.productStoreForm.productId);
              this.getList()
            }).finally(f => {
              this.btnLoading = false
            });
          } else {
            if (sign === 1) {
              this.$message.error("入库数量大于仓库容量请修改后重新保存")
            } else if (sign === 2) {
              this.$message.error("出库数量大于商品库存请修改后重新保存")
            }
          }
        }
      });
    },
    /** 关闭出入库弹窗 */
    productStoreCancel(){
      this.openStoreSetting = false
      this.productStoreForm.operatorNum = 0
    }
  }
};
</script>
<style scoped>
.addressTitle{
  width: 90px;
  text-align: right;
  padding-right: 12px;
  line-height: 32px;
  font-size: 14px;
  color: #606266;
  font-weight: bold;
}

/deep/ .el-form-item--medium .el-form-item__content{
  line-height: 32px !important;
}
/deep/ .el-select{
  width: 100%;
}
</style>
